<template>
  <!-- 主体部分 -->
  <section class="main">
    <input id="toggle-all" class="toggle-all" type="checkbox" :checked="all" @change="changeAll(!all)" />
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <!-- 如果显示编辑效果可以为li添加editing类名 如果要显示完成状态可以添加completed类名 -->
      <li :class="{completed:item.flag,editing:item.id===editId}" v-for="item in myList" :key="item.id">
        <div class="view">
          <input class="toggle" type="checkbox" :checked="item.flag" @change="changeFlag(item.id)" />
          <label @dblclick="showEdit(item.id)">{{item.name}}</label>
          <button class="destroy" @click="remove(item.id)"></button>
        </div>
        <input class="edit" :value="item.name" v-focus1 @keyup.enter="saveEdit(item.id,$event.target.value)" @blur="saveEdit(item.id,$event.target.value)" />
      </li>
    </ul>
  </section>
</template>

<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
export default {
  name: 'TodoMain',
  data () {
    return {
      editId: -1
    }
  },
  methods: {
    ...mapMutations(['changeFlag', 'remove', 'changeAll']),
    showEdit (id) {
      this.editId = id
    },
    saveEdit (id, newVal) {
      this.editId = -1
      this.$store.commit('save', { id, newVal })
    }
  },
  computed: {
    ...mapState(['list']),
    ...mapGetters(['myList', 'all'])
  },
  watch: {
    list: {
      handler () {
        window.localStorage.setItem('todos', JSON.stringify(this.list))
      },
      deep: true
    }
  }
}
</script>

<style scoped lang="less">
</style>
